import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
    state:{
        todoList:JSON.parse(localStorage.getItem('todos')) || []
    },
    actions:{
        add({commit},todoName){
            commit('addTodo',todoName)
        }
    },

    mutations:{
        addTodo(state,todoName){
            let id = state.todoList.length ? state.todoList[state.todoList.length - 1].id + 1 : 1
            const stateObj = {
                id,
                todoName,
                isDone:false,
            }
            state.todoList.push(stateObj)
        },

        updeleteTodo(state,id){
            state.todoList.forEach(item=>{
                if(item.id === id){
                    item.isDone = !item.isDone
                }
            })
        },
        deleteTodo(state,id){
            state.todoList = state.todoList.filter(item=>{
                return item.id !== id
            })
        },
        updeleteAll(state){
             const result = state.todoList.every(item=>item.isDone)
            state.todoList.forEach(item=>{
                item.isDone = !result
            })
        },
        deleteTodoDone(state){
            state.todoList = state.todoList.filter(item=>!item.isDone)
        }
    },

})